import os

from flask import Blueprint, render_template, request, current_app

upload_bp = Blueprint('upload', __name__)


@upload_bp.route('/upload', methods=['GET'])
def upload_file():
    # 获取自定义 logger
    logger = current_app.config['custom_logger'].get_logger()
    logger.info('跳转到上传页面')
    return render_template('upload.html')


@upload_bp.route('/uploader', methods=['POST'])
def uploader():
    if request.method == 'POST':
        f = request.files['file']
        upload_folder = current_app.config['UPLOAD_FOLDER']

        # 检查目录是否存在，不存在则创建
        if not os.path.exists(upload_folder):
            os.makedirs(upload_folder)

        file_path = os.path.join(upload_folder, f.filename)
        f.save(file_path)
        # 获取自定义 logger
        logger = current_app.config['custom_logger'].get_logger()
        logger.info('文件上传成功')
        return 'file uploaded successfully'
